﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using S7.Net;
using S7200SmartDll;

namespace PLC
{
    class PLCManager
    {

        private static PLCManager pLCManager = null;
        private static S7200SmartClient plc =null;

        private static String _ip = "192.168.2.1";
        private static int _rack = 0;
        private static int _slot = 1;
        private static ushort _connectionType = 3;
        

   
        private PLCManager()
        {
 
        }

        public static PLCManager GetInstance(String ip,int rack,int slot,ushort connectionType)
        {
            _ip = ip;
            _rack = rack;
            _slot = slot;
            _connectionType = connectionType;
            if (pLCManager == null)
            {
                plc = new S7200SmartClient();
                plc.SetConnectionType(connectionType);  
                pLCManager = new PLCManager();
            }
            return pLCManager;
        }

        private Boolean isConnected =false;

        public bool IsConnected { get => isConnected; set => isConnected = value; }

        public int Connect()
        {
            if (isConnected)
            {
                return 0;
            }

            int ret = plc.ConnectTo(_ip, _rack, _slot,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            if (ret == 0)
            {
                // 连接成功
                isConnected = true;

            }
            else
            {
                isConnected = false;
                
            }
            return ret;
        }

        public void Close()
        {
            if (isConnected)
            {
                plc.Disconnect();
                IsConnected = false;
            }
        }

        public float readVData(int start)
        {
            return plc.VRead_REAL(start);
        }


    } 
}
